package cn.car.utils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;

public class SemaphoreUtil {

    private static ConcurrentMap<String, Semaphore> cameraMap = new ConcurrentHashMap<>();


    public static Semaphore get(String ip) {
        // 第一次检查：如果实例已存在，直接返回，避免进入同步块
        Semaphore semaphore = cameraMap.get(ip);
        if (semaphore == null) {
            // 同步块，保证只有一个线程进入
            synchronized (SemaphoreUtil.class) {
                // 第二次检查：在同步块内再次检查，防止多个线程同时通过第一次检查
                if (semaphore == null) {
                    // 创建实例
                    semaphore = new Semaphore(1);
                    cameraMap.put(ip, semaphore);
                }
            }
        }
        return semaphore;
    }


    public static void tryAcquire(String ip) throws InterruptedException {
        Semaphore semaphore = get(ip);
        boolean b = semaphore.tryAcquire();

        if (!b) {
            throw new InterruptedException();
        }
    }

    public static void release(String ip) {
        Semaphore semaphore = get(ip);
        semaphore.release();

    }



}
